package com.zenithmind.version.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import com.zenithmind.common.utils.BeanCopyUtils;
import com.zenithmind.version.pojo.domain.Branch;
import com.zenithmind.version.pojo.dto.BranchCreateDTO;
import com.zenithmind.version.pojo.dto.BranchUpdateDTO;
import com.zenithmind.version.pojo.query.BranchQueryDTO;
import com.zenithmind.version.pojo.vo.BranchVO;
import com.zenithmind.version.service.BranchService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 分支管理控制器
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Tag(name = "分支管理", description = "分支管理相关接口")
@RestController
@RequestMapping("/api/v1/branches")
@RequiredArgsConstructor
public class BranchController {

    private final BranchService branchService;

    @Operation(summary = "创建分支", description = "创建新的分支")
    @PostMapping
    public Result<BranchVO> createBranch(@Valid @RequestBody BranchCreateDTO createDTO) {
        BranchVO branch = branchService.createBranch(createDTO);
        return Result.success(branch);
    }

    @Operation(summary = "更新分支", description = "更新分支信息")
    @PutMapping("/{id}")
    public Result<Boolean> updateBranch(
            @Parameter(description = "分支ID") @PathVariable String id,
            @Valid @RequestBody BranchCreateDTO updateDTO) {
        Boolean result = branchService.updateBranch(id, updateDTO);
        return Result.success(result);
    }

    @Operation(summary = "删除分支", description = "删除指定分支")
    @DeleteMapping("/{id}")
    public Result<Boolean> deleteBranch(@Parameter(description = "分支ID") @PathVariable String id) {
        Boolean result = branchService.deleteBranch(id);
        return Result.success(result);
    }

    @Operation(summary = "批量删除分支", description = "批量删除分支")
    @DeleteMapping("/batch")
    public Result<Boolean> batchDeleteBranches(@RequestBody List<String> ids) {
        // 循环删除每个分支
        for (String id : ids) {
            branchService.deleteBranch(id);
        }
        return Result.success(true);
    }

    @Operation(summary = "分页查询分支", description = "分页查询分支列表")
    @GetMapping("/page")
    public Result<PageResult<BranchVO>> getBranchPage(
            @Parameter(description = "当前页") @RequestParam(defaultValue = "1") Long current,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "10") Long size,
            @Parameter(description = "仓库ID") @RequestParam(required = false) String repositoryId,
            @Parameter(description = "分支状态") @RequestParam(required = false) Integer status,
            @Parameter(description = "分支类型") @RequestParam(required = false) Integer type,
            @Parameter(description = "关键词") @RequestParam(required = false) String keyword) {
        PageResult<BranchVO> page = branchService.getBranchPage(current, size, repositoryId, status, type, keyword);
        return Result.success(page);
    }

    @Operation(summary = "获取分支详情", description = "获取分支详细信息")
    @GetMapping("/{id}")
    public Result<BranchVO> getBranchDetail(@Parameter(description = "分支ID") @PathVariable String id) {
        Branch branch = branchService.getById(id);
        BranchVO branchVO = BeanCopyUtils.copyBean(branch, BranchVO.class);
        return Result.success(branchVO);
    }

    @Operation(summary = "获取仓库分支", description = "获取仓库的分支列表")
    @GetMapping("/repository/{repositoryId}")
    public Result<List<BranchVO>> getRepositoryBranches(
            @Parameter(description = "仓库ID") @PathVariable String repositoryId,
            @Parameter(description = "分支状态") @RequestParam(defaultValue = "1") Integer status) {
        List<BranchVO> branches = branchService.getRepositoryBranches(repositoryId, status);
        return Result.success(branches);
    }

    @Operation(summary = "根据名称获取分支", description = "根据分支名称获取分支信息")
    @GetMapping("/repository/{repositoryId}/name/{branchName}")
    public Result<BranchVO> getBranchByName(
            @Parameter(description = "仓库ID") @PathVariable String repositoryId,
            @Parameter(description = "分支名称") @PathVariable String branchName) {
        // 暂时返回空，需要实现具体逻辑
        return Result.success(null);
    }

    @Operation(summary = "获取默认分支", description = "获取仓库的默认分支")
    @GetMapping("/repository/{repositoryId}/default")
    public Result<BranchVO> getDefaultBranch(@Parameter(description = "仓库ID") @PathVariable String repositoryId) {
        // 暂时返回空，需要实现具体逻辑
        return Result.success(null);
    }

    @Operation(summary = "设置默认分支", description = "设置仓库的默认分支")
    @PostMapping("/repository/{repositoryId}/default/{branchId}")
    public Result<Boolean> setDefaultBranch(
            @Parameter(description = "仓库ID") @PathVariable String repositoryId,
            @Parameter(description = "分支ID") @PathVariable String branchId) {
        Boolean result = branchService.setDefaultBranch(repositoryId, branchId);
        return Result.success(result);
    }

    @Operation(summary = "合并分支", description = "合并分支")
    @PostMapping("/merge")
    public Result<Boolean> mergeBranch(
            @Parameter(description = "源分支ID") @RequestParam String sourceBranchId,
            @Parameter(description = "目标分支ID") @RequestParam String targetBranchId,
            @Parameter(description = "合并消息") @RequestParam(defaultValue = "Merge branch") String mergeMessage) {
        Boolean result = branchService.mergeBranch(sourceBranchId, targetBranchId, mergeMessage);
        return Result.success(result);
    }

    @Operation(summary = "检查合并冲突", description = "检查分支合并冲突")
    @GetMapping("/merge/conflicts")
    public Result<String> checkMergeConflicts(
            @Parameter(description = "源分支ID") @RequestParam String sourceBranchId,
            @Parameter(description = "目标分支ID") @RequestParam String targetBranchId) {
        String conflicts = branchService.checkMergeConflicts(sourceBranchId, targetBranchId);
        return Result.success(conflicts);
    }

    @Operation(summary = "比较分支", description = "比较两个分支的差异")
    @GetMapping("/compare")
    public Result<String> compareBranches(
            @Parameter(description = "源分支ID") @RequestParam String sourceBranchId,
            @Parameter(description = "目标分支ID") @RequestParam String targetBranchId) {
        String differences = branchService.compareBranches(sourceBranchId, targetBranchId);
        return Result.success(differences);
    }

    @Operation(summary = "获取分支提交", description = "获取分支的提交历史")
    @GetMapping("/{repositoryId}/{branchName}/commits")
    public Result<List<Object>> getBranchCommits(
            @Parameter(description = "仓库ID") @PathVariable String repositoryId,
            @Parameter(description = "分支名称") @PathVariable String branchName,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "50") Integer limit) {
        List<Object> commits = branchService.getBranchCommits(repositoryId, branchName, limit);
        return Result.success(commits);
    }

    @Operation(summary = "搜索分支", description = "根据关键词搜索分支")
    @GetMapping("/search")
    public Result<List<BranchVO>> searchBranches(
            @Parameter(description = "仓库ID") @RequestParam String repositoryId,
            @Parameter(description = "关键词") @RequestParam String keyword,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        List<BranchVO> branches = branchService.searchBranches(repositoryId, keyword, limit);
        return Result.success(branches);
    }

    @Operation(summary = "获取我的分支", description = "获取用户创建的分支")
    @GetMapping("/my")
    public Result<List<BranchVO>> getUserBranches(
            @Parameter(description = "仓库ID") @RequestParam(required = false) String repositoryId,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "20") Integer limit) {
        String userId = UserContext.getUserId();
        List<BranchVO> branches = branchService.getUserBranches(userId, repositoryId, limit);
        return Result.success(branches);
    }

    @Operation(summary = "获取活跃分支", description = "获取活跃的分支列表")
    @GetMapping("/repository/{repositoryId}/active")
    public Result<List<BranchVO>> getActiveBranches(
            @Parameter(description = "仓库ID") @PathVariable String repositoryId,
            @Parameter(description = "限制数量") @RequestParam(defaultValue = "10") Integer limit) {
        List<BranchVO> branches = branchService.getActiveBranches(repositoryId, limit);
        return Result.success(branches);
    }

    @Operation(summary = "获取分支统计", description = "获取分支统计信息")
    @GetMapping("/repository/{repositoryId}/statistics")
    public Result<Object> getBranchStatistics(@Parameter(description = "仓库ID") @PathVariable String repositoryId) {
        Object statistics = branchService.getBranchStatistics(repositoryId);
        return Result.success(statistics);
    }

    @Operation(summary = "检查分支名称", description = "检查分支名称是否存在")
    @GetMapping("/check-name")
    public Result<Boolean> checkBranchNameExists(
            @Parameter(description = "仓库ID") @RequestParam String repositoryId,
            @Parameter(description = "分支名称") @RequestParam String branchName,
            @Parameter(description = "排除的分支ID") @RequestParam(required = false) String excludeId) {
        Boolean exists = !branchService.checkBranchNameAvailable(branchName, repositoryId);
        return Result.success(exists);
    }

    @Operation(summary = "保护分支", description = "设置分支保护状态")
    @PostMapping("/{id}/protect")
    public Result<Boolean> protectBranch(
            @Parameter(description = "分支ID") @PathVariable String id,
            @Parameter(description = "是否保护") @RequestParam Boolean isProtected) {
        Boolean result = branchService.setProtectedBranch(id, isProtected);
        return Result.success(result);
    }

    @Operation(summary = "归档分支", description = "设置分支归档状态")
    @PostMapping("/{id}/archive")
    public Result<Boolean> archiveBranch(
            @Parameter(description = "分支ID") @PathVariable String id,
            @Parameter(description = "是否归档") @RequestParam Boolean isArchived) {
        Boolean result = branchService.archiveBranch(id, isArchived);
        return Result.success(result);
    }
}
